﻿var curFilePath = "";
var Html_Build = "";
var uploadInst;
var uploadOption;
var upIns;

$(function () {
    //得到 upload 对象
    uploadInst = layui.upload;
    //加载上传
    InitUploadInst();
    //加载文件列表
    InitFileManager();

    //组装HTML
    function MakeHtml(item, ft) {
        Html_Build = "";
        //先处理路径问题
        //解决win下面\问题  把\替换为/
        var src = (item["CurPath"] + "/" + item["Name"]).replace(/\\/g, "/");
        //文件路径
        var path = item["Type"] == "Directory" ? (item["CurPath"] + "/").replace(/\\/g, "/") : ((item["CurPath"] + "/" + item["Name"]).replace(/\\/g, "/"));

        //解决linux问题 
        src = ("/" + src).replace("//", "/");
        path = ("/" + path).replace("//", "/");

        var dir = item["CurPath"];
        if (dir.indexOf("/") != -1) {
            dir = "\\" + dir.replace("/", "\\") + "\\";
        } 

        //图片
        if (ft == "layui-icon-picture") {

            if (!appConfig.IsLinux) {
                Html_Build += "<div class=\"file_item filelists\" data-path=\"" + path + "\" data-dir=\"" + dir + "\" data-filename=\"" + item["Name"] + "\" data-suffix=\"" + item["Suffix"] + "\" data-type=\"" + item["Type"] + "\">";
                Html_Build += "    <img style=\"margin-left:1px;\" src=\"" + src + "?width=148&height=132&bgcolor=FFFFFF\" />";
                Html_Build += "    <p class=\"file_title\" title=\"" + item["Name"] + "\">" + item["Name"] + "</p>";
                Html_Build += "</div>";
            } else {
                //linux
                Html_Build += "<div class=\"file_item filelists\" data-path=\"" + path + "\" data-dir=\"" + dir + "\" data-filename=\"" + item["Name"] + "\" data-suffix=\"" + item["Suffix"] + "\" data-type=\"" + item["Type"] + "\">";
                Html_Build += "<div data-imgurl=\"" + src + "\" ></div>";
                Html_Build += "    <p class=\"file_title\" title=\"" + item["Name"] + "\">" + item["Name"] + "</p>";
                Html_Build += "</div>";
            }

        }
        //视频
        else if (ft == "layui-icon-video") {
            Html_Build += "<div class=\"file_item filelists\" data-path=\"" + path + "\" data-dir=\"" + dir + "\" data-filename=\"" + item["Name"] + "\" data-suffix=\"" + item["Suffix"] + "\" data-type=\"" + item["Type"] + "\">";
            Html_Build += "    <div style=\"height:107px;width:150px;text-align:center;padding-top:25px;\"><i class=\"layui-icon layui-icon-video\" style=\"font-size:80px; color:#555555\"></i></div>";
            Html_Build += "    <p class=\"file_title\" title=\"" + item["Name"] + "\">" + item["Name"] + "</p>";
            Html_Build += "</div>";
        }
        //文件夹
        else if (ft == "layui-icon-export") {
            Html_Build += "<div class=\"file_item filelists\" data-path=\"" + path + "\" data-dir=\"" + dir + "\" data-filename=\"" + item["Name"] + "\" data-suffix=\"" + item["Suffix"] + "\" data-type=\"" + item["Type"] + "\">";
            Html_Build += "    <div style=\"height:107px;width:150px;text-align:center;padding-top:25px;\"><i class=\"layui-icon layui-icon-export\" style=\"font-size:80px; color:#555555\"></i></div>";
            Html_Build += "    <p class=\"file_title\" title=\"" + item["Name"] + "\">" + item["Name"] + "</p>";
            Html_Build += "</div>";
        }
        //其他
        else {
            Html_Build += "<div class=\"file_item filelists\" data-path=\"" + path + "\" data-dir=\"" + dir+ "\" data-filename=\"" + item["Name"] + "\" data-suffix=\"" + item["Suffix"] + "\" data-type=\"" + item["Type"] + "\">";
            Html_Build += "    <div style=\"height:107px;width:150px;text-align:center;padding-top:25px;\"><i class=\"layui-icon layui-icon-file\" style=\"font-size:80px; color:#555555\"></i></div>";
            Html_Build += "    <p class=\"file_title\" title=\"" + item["Name"] + "\">" + item["Name"] + "</p>";
            Html_Build += "</div>";
        }
        return Html_Build;
    }

    //组装ICON
    function MakeIcon(item) {
        var ft = "file-o";
        switch (item.Suffix.toLowerCase()) {
            case "":
                ft = "layui-icon-export";
                break;
            case ".jpg":
            case ".png":
            case ".bmp":
            case ".jpeg":
            case ".gif":
                ft = "layui-icon-picture";
                break;
            case ".mp3":
                ft = "layui-icon-headset";
                break;
            case ".mp4":
            case ".flv":
                ft = "layui-icon-video";
                break;
            case ".cs":
            case ".js":
            case ".css":
            case ".html":
            case ".aspx":
                ft = "layui-icon-fonts-code";
                break;
            default:
                ft = "layui-icon-file";
                break;
        }

        Html_Build = MakeHtml(item, ft);
        // console.log(Html_Build);
        $(".tab-content").append(Html_Build);
        //$(".filelist-tab-content").append(Html_Build);
    }

    //加载文件列表
    function loadfilelist(dir) {
        //console.log(dir);
        curFilePath = dir + "/";
        dir = dir.replace(ctrConfig.FileRootPath, ""); //替换掉根目录 , 首位符顺便也换掉
        dir = dir.replace(/\\/g, "/");
        //console.log(dir);
        layer.load();//加载中
        var url = appConfig.adminPath + "ashx/filemanage.ashx";
        var data = { dir: (arguments.length == 0 ? "/" : dir) };
        AjaxSubmit(url, "getlist", data, function (f, d) {
            $(".curpath").text(dir.replace(/\//g, "\\").replace('\\\\', '\\'));

            // console.log(dir.replace(/\//g, "\\").replace('\\\\', '\\'));
            //location.hash = dir;
            //console.log(f, d);
            layer.closeAll('loading');

            if (f == 1) {
                if (d.result == -99) {
                    layer.alert("登录超时，请重新登录后再试");
                } else {
                    //uploadPlugin.folder = dir.trimStart('/');
                    $(".tab-content").html("");
                    //console.log(d.returnval);
                    d.returnval = d.returnval.reverse();
                    $.each(d.returnval, function (i, e) {

                        //console.log(e);
                        MakeIcon(e);
                    });

                    //linux下才有这个元素div[data-imgurl]
                    $("div[data-imgurl]").each(function (i, e) {
                        var imgsrc = $(e).attr("data-imgurl");
                        cutImg(imgsrc, 148, 132, $(e), "#fff");
                    });

                    $(".tab-content").append("<div style=\"clear:both\"></div>");
                    //重载上传插件
                    upIns.config.headers = {
                        Folder: FormatPath()
                    };
                    uploadInst.render(upIns);
                }
                //InitFileContextMenu();
            }
            else {
                layer.alert("加载失败,请刷新页面重试");
            }
        });
    }

    function InitFileManager() {
        if (location.hash == "") {
            loadfilelist("/");
        }
        else {
            //loadfilelist(location.hash.trimStart('#'));
        }
    }

    function FormatPath(path) {
        if (arguments.length == 0) {
            path = curFilePath;
        }
        path = path.replace("\\" + ctrConfig.FileRootPath, "");
        path = path.replace(/\\/g, "/");
        if (path.length > 1) {
            path = path.substring(1, path.length);
        }
        if (path == "/") {
            path = "";
        }


        return path;
    }

    //双击的时候 如果是图片文件就打开
    $("body").delegate(".filelists", "dblclick ", function () {
        var _this = $(this);
        var dir = _this.attr("data-dir");
        var type = _this.attr("data-type");

        if (type == "Directory") {
            if (dir != "") {
                loadfilelist(dir);
            }
        }
        else {
            viewfiles(_this.data());
            //console.log("赋值");
        }
    });

    //单击选中
    $("body").delegate(".filelists", "click", function () {

        var _this = $(this);
        if (_this.attr("data-type") == "Directory") {
            return false;
        }

        var isSelect = _this.hasClass("select");

        if (!isMultiple) {
            //只能单选
            $(".filelists").removeClass("select");
        }

        if (isSelect) {
            _this.removeClass("select");
        }
        else {
            _this.addClass("select");
        }
    });

    //主页
    $(".action-home").on("click", function () {
        loadfilelist("/");
    });

    //返回
    $(".action-up").on("click", function () {
        var curpath = $(".curpath").text();
        if (curpath == "" || curpath == "\\") {
            return false;
        }
        else {
            curpath = curpath.substring(0, curpath.lastIndexOf('\\'));
            if (curpath == "") {
                loadfilelist("/");
            }
            else {
                loadfilelist(curpath);
            }
        }
    });

    //刷新
    $(".action-refresh").on("click", function () {
        var curpath = $(".curpath").text();
        loadfilelist(curpath);
    });


    //新建文件夹
    $(".action-newfolder").on("click", function () {
        var layloadid = 0;
        layer.prompt({ title: "文件夹名称 (仅允许字母和数字)" }, function (value, index, elem) {
            var res = value;
            if (res == "" || res == null) {
                //如果是空或者null , 放弃创建
            }
            else {
                if (/^[A-Za-z0-9]+$/.test(res)) {
                    //可以进行下一步了
                    var curpath = $(".curpath").text().replace(/\\/g, "/");
                    layloadid = layer.load();
                    //loading("正在创建文件夹 , 请稍后");
                    var url = appConfig.adminPath + "ashx/filemanage.ashx";
                    var data = { dir: curpath, newdir: res };
                    AjaxSubmit(url, "createfolder", data, function (f, d) {
                        ///console.log(f, d);
                        layer.close(layloadid);
                        if (f == 1) {
                            if (d.result == -99) {
                                layer.msg("登录超时 , 请重新登录");
                            } else {
                                layer.close(index);
                                //创建成功
                                loadfilelist($(".curpath").text());
                                //$(".tab-content").html("");
                                //$(".tab-content").append("<div style=\"clear:both\"></div>");
                            }
                        }
                        else {
                            layer.msg("加载失败,请刷新页面重试");
                        }
                    });
                }
                else {
                    // 文件名不支持
                    layer.msg("文件夹名称只允许为数字或者字母及其组合");
                    return false;
                }
            }
        });
    });


    function InitUploadInst() {
        //创建一个上传组件
        uploadOption = {
            elem: '#uploadFile'
            , url: '../ashx/upload.ashx'
            , headers: {
                Folder: FormatPath()
            }
            , multiple: true
            , before: function (obj) { //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                layer.load(); //上传loading
            }
            , progress: function (n) {
                var percent = n + '%' //获取进度百分比
                //element.progress('demo', percent); //可配合 layui 进度条元素使用
            }
            , done: function (res, index, upload) { //上传后的回调
                console.log(res, index, upload);
            }
            , allDone: function (obj) { //当文件全部被提交后，才触发
                layer.closeAll('loading');
                if (obj.aborted > 0) {
                    //有失败的 , 需要提示
                    layer.alert("总共" + obj.total + "个文件<br/>" + obj.successful + "个文件上传成功</br>" + obj.aborted + "个文件上传失败", {
                        icon: 7,
                        title: "文件上传失败提示"
                    });
                }
                else {
                    layer.msg(obj.total + "个文件上传成功");
                    var curpath = $(".curpath").text();
                    loadfilelist(curpath);
                }
                //console.log(obj.total); //得到总文件数
                //console.log(obj.successful); //请求成功的文件数
                //console.log(obj.aborted); //请求失败的文件数
            }
            , error: function (index, upload) {
                layer.closeAll('loading'); //关闭loading
            }
            , accept: 'BMP|JPEG|JPG|GIF|PNG|TIFF|TXT|DOC|DOCX|RAR|ZIP|XLS|XLSX|PDF|MP4|MP3|IPK|APK' //允许上传的文件类型
            , size: 60200 //最大允许上传的文件大小  50MB
        };

        upIns = uploadInst.render(uploadOption);

    }

    /**
    * canvas画图
    * @param imgsrc 图片路径
    * @param width canvas宽
    * @param height canvas高
    * @param container 容器
    * @param bgColor canvas背景颜色
    */
    function cutImg(imgsrc, width, height, container, bgColor) {
        var count = 0;
        var defaultImg = "/SysRes/images/no_img_manager.png";//加载错误默认显示的图片
        var img = document.createElement("img");
        img.src = imgsrc;
        var cvs = document.createElement("canvas");
        cvs.width = width;
        cvs.height = height;
        var context = cvs.getContext('2d');
        context.fillStyle = bgColor;
        context.rect(0, 0, width, height);
        context.fill();
        appendCvs(container);
        function appendCvs(container) {
            if (typeof container == "object") {
                container.html("").append(cvs);
            } else {
                var _container = document.querySelector(container);
                _container.innerHTML = "";
                _container.appendChild(cvs);
            }
        }
        var rate = width / height;
        img.onload = function () {
            var imgWidth = img.width, imgHeight = img.height;
            var rate = imgWidth / imgHeight;
            var dx, dy, sx, sy, cvsw = width, cvsh = height, cvsx = 0, cvsy = 0;
            if (imgWidth <= width && imgHeight <= height) {//宽高都小于canvas尺寸
                dx = imgWidth, dy = imgHeight;
                sx = 0, sy = 0;
                if (rate > 1) {
                    cvsw = width, cvsh = cvsw / rate;
                    cvsx = 0, cvsy = (height - cvsh) / 2;
                } else {
                    cvsh = height, cvsw = cvsh * rate;
                    cvsy = 0, cvsx = (width - cvsw) / 2;
                }
            } else if (rate < 1) {//宽度小于高度时
                dx = imgWidth, dy = dx;
                sx = 0, sy = (imgHeight - dy) / 2;
            } else {//高度小于宽度时
                dx = imgHeight, dy = dx;
                sx = (imgWidth - dx) / 2, sy = 0;
            }
            context.drawImage(img, sx, sy, dx, dy, cvsx, cvsy, cvsw, cvsh);
            //var dataImg=cvs.toDataURL("image/jpeg");
            appendCvs(container);
        }
        img.onerror = function () {
            count++;//防止图片一直加载不出来造成死循环
            (count < 2) && cutImg(defaultImg, width, height, container, bgColor);
        }
    }
});

